package tr.edu.metu.is.mega.client.course.student;

import gwtupload.client.IUploader;
import gwtupload.client.IUploader.OnFinishUploaderHandler;
import gwtupload.client.SingleUploader;
import tr.edu.metu.is.mega.client.core.EditDialog;
import tr.edu.metu.is.mega.client.resource.MEGAResourceBundle;
import tr.edu.metu.is.mega.client.resource.MEGAResources;
import tr.edu.metu.is.mega.client.resource.MegaConstants;
import tr.edu.metu.is.mega.client.widgets.MegaTextField;
import tr.edu.metu.is.mega.common.dto.TeamDTO;

import com.extjs.gxt.ui.client.widget.form.AdapterField;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.layout.FormData;

/**
 * Edit dialog for teams.
 */
public class TeamInformationEditDialog extends EditDialog<TeamDTO> {

    private MEGAResourceBundle resourceBundle;

    private MegaTextField teamNameField;

    private TeamDTO teamDTO;

    private MegaTextField filePathField;

    private SingleUploader uploader;

    /**
     * Default constructor.
     */
    public TeamInformationEditDialog() {
        super(TeamDTO.class.getName());

    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void initForm(FormPanel parent, Object... params) {
        setSize(340, 200);

        resourceBundle = MEGAResources.RESOURCEBUNDLE;

        teamNameField = new MegaTextField(TeamDTO.FIELD_TEAM_NAME);
        teamNameField.setFieldLabel(resourceBundle.teamManagementTeamName());
        parent.add(teamNameField, new FormData("96%"));

        filePathField = new MegaTextField(TeamDTO.FIELD_LOGO);
        filePathField.setFieldLabel("File Name");
        filePathField.setEnabled(false);
        parent.add(filePathField, new FormData("90%"));

        uploader = new SingleUploader();
        uploader.addOnFinishUploadHandler(new OnFinishUploaderHandler() {

            @Override
            public void onFinish(IUploader uploader) {
                filePathField.setValue(uploader.getServerInfo().message);
            }
        });
        AdapterField field = new AdapterField(uploader);
        field.setFieldLabel("File");
        parent.add(field, new FormData("90%"));

    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected TeamDTO guiToDTO() {
        teamDTO.setTeamName(teamNameField.getValue());
        teamDTO.setLogo(filePathField.getValue());
        return teamDTO;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void dtoToGUI(TeamDTO dto) {
        teamDTO = dto;
        teamNameField.setValue(dto.getTeamName());
        filePathField.setValue(dto.getLogo());
        uploader.setFileInputPrefix(MegaConstants.TEAM_PATH + dto.getPkid() + "/");
    }

}
